package br.ufrgs.meetappsoapserver;

import java.util.Iterator;

import javax.xml.bind.JAXB;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SAAJResult;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.dom.DOMSource;

import br.ufrgs.meetappsoapserver.jaxws.CreateMeeting;
import br.ufrgs.meetappsoapserver.jaxws.Update;

public class ServerSOAPHandler {

	private static final String NAMESPACE_URI = "http://example.com/";
	private static final QName CREATE_MEETING = new QName(NAMESPACE_URI,
			"createMeeting");
	private static final QName UPDATE = new QName(NAMESPACE_URI,
			"update");

	private MessageFactory messageFactory;
	private ServerAdapter serverAdapter;

	public ServerSOAPHandler() throws SOAPException {
		messageFactory = MessageFactory.newInstance();
		serverAdapter = new ServerAdapter();
	}

	public SOAPMessage handleSOAPRequest(SOAPMessage request)
			throws SOAPException {
		SOAPBody soapBody = request.getSOAPBody();
		Iterator iterator = soapBody.getChildElements();
		Object responsePojo = null;
		while (iterator.hasNext()) {
			Object next = iterator.next();
			if (next instanceof SOAPElement) {
				SOAPElement soapElement = (SOAPElement) next;
				QName qname = soapElement.getElementQName();
				if (CREATE_MEETING.equals(qname)) {
					handleCreateMeetingRequest(soapElement);
					break;
				} else if (UPDATE.equals(qname)) {
					responsePojo = handleUpdateRequest(soapElement);
					break;
				}
			}
		}
		SOAPMessage soapResponse = messageFactory.createMessage();
		soapBody = soapResponse.getSOAPBody();
		if (responsePojo != null) {
			JAXB.marshal(responsePojo, new SAAJResult(soapBody));
		} //else {
//			SOAPFault fault = soapBody.addFault();
//			fault.setFaultString("Unrecognized SOAP request.");
//		}
		return soapResponse;
	}

	private void handleCreateMeetingRequest(SOAPElement soapElement) {
		CreateMeeting createMeetingRequest = JAXB.unmarshal(new DOMSource(soapElement),
				CreateMeeting.class);
		serverAdapter.createMeeting(createMeetingRequest);
	}

	private Object handleUpdateRequest(SOAPElement soapElement) {
		Update sayGoodbyeRequest = JAXB.unmarshal(
				new DOMSource(soapElement), Update.class);
		return serverAdapter.update(sayGoodbyeRequest);
	}
}
